package com.lalosoft.misgastos.activities;

import java.sql.SQLException;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

import com.lalosoft.misgastos.R;
import com.lalosoft.misgastos.config.GastosManager;
import com.lalosoft.misgastos.domain.Item;
import com.lalosoft.misgastos.listener.DeleteItemListener;
import com.lalosoft.misgastos.service.GastosTarjetaService;
import com.lalosoft.misgastos.service.impl.GastosTarjetaServiceImpl;
import com.lalosoft.misgastos.view.ItemListView;

public class ItemListActivity extends Activity {
	
	private ItemListView listView;
	private TextView actualMonth;
	private static String TAG = "ItemListActivity";
	private Context context = ItemListActivity.this;
	private DeleteItemListener actionItemListener;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list);
		actualMonth = (TextView) findViewById(R.id.item_list_actual_month);
		listView = (ItemListView) findViewById(R.id.items_listview);
		actionItemListener = new DeleteItemListener() {
			
			@Override
			public void deleteItem(Item item) {
				try {
					GastosManager.getInstance(context).deleteItem(item);
					DeleteItemTask task = new DeleteItemTask();
					task.execute(item);
					Log.d(TAG, "Se ha borrado el item: " + item.getDetalle());
				} catch (SQLException e) {
					Log.e(TAG, "Error en borrar item: " + e.getMessage());
				}
			}

			@Override
			public void deleteAllItems(String token) {
				try {
					GastosManager.getInstance(context).deleteAllItems();
					DeleteAllItemsTask task = new DeleteAllItemsTask();
					task.execute(GastosManager.getInstance(context).getCurrentAccount().getUserToken());
				} catch (SQLException e) {
					Log.e(TAG, "Error en borrar item: " + e.getMessage());
				}
			}
		};
		listView.setActionItemListener(actionItemListener);
		init();
	}

	private void init() {
		Log.i(TAG, "INIT ITEM LIST");
		showMonth();
		List<Item> list = new ArrayList<Item>();
		try {
			list = GastosManager.getInstance(context).getAllItems();
		} catch (SQLException e) {
			Log.e(TAG, "ERROR EN GETALLITEMS");
		}
		if(list.size() > 0){
			listView.setItemList(list);
		} else {
			Intent i = new Intent(context, MainActivity.class);
			startActivity(i);
			finish();
		}
		
		Log.i(TAG, "SE SETEARON LOS ITEMS");
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		int menuId = 0;
		if(GastosManager.getInstance(context).avisosMensualesActivado()){
			menuId = R.menu.menu;
		} else {
			menuId = R.menu.menu_2;
		}
		inflater.inflate(menuId, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected (MenuItem item){
		
		switch (item.getItemId()) {
		case R.id.menu_delete_all: {
			actionItemListener.deleteAllItems(GastosManager.getInstance(context).getCurrentAccount().getUserToken());
			Intent intent = getIntent();
			finish();
			startActivity(intent);
//			try {
////				GastosManager.getInstance(context).deleteAllItems();
//				actionItemListener.deleteAllItems(GastosManager.getInstance(context).getCurrentAccount().getUserToken());
//				Intent intent = getIntent();
//				finish();
//				startActivity(intent);
//				Log.d(TAG, "Se han borrado todos los items!!");
//			} catch (SQLException e) {
//				Log.e(TAG, "Error al eliminar todos los items: " + e.getMessage());
//			}
		}break;
		case R.id.item1: {
			final AlertDialog.Builder builder = new Builder(context);
			builder.setTitle("Total a pagar");
			double total = getTotalMonth();
			builder.setMessage("Total del mes = " + total);
			builder.setPositiveButton("Ok", new OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
				
			});
			builder.show();
		} break;
		case R.id.menu_cancel:{
			GastosManager.getInstance(context).avisosMensuales(false);
			Toast.makeText(context, "Se han cancelado los avisos mensuales de gastos", Toast.LENGTH_SHORT).show();
			Log.i(TAG, "SE DESACTIVARON LOS AVISOS");
			backToMain();
		} break;
		case R.id.menu_activar:{
			GastosManager.getInstance(context).avisosMensuales(true);
			Toast.makeText(context, "Se han activado los avisos mensuales de gastos", Toast.LENGTH_SHORT).show();
			
			Log.i(TAG, "SE ACTIVARON LOS AVISOS");
			backToMain();
		}break;
		}

		return true;
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if (keyCode == KeyEvent.KEYCODE_BACK) {
	    	backToMain();
	    }
	    return super.onKeyDown(keyCode, event);
	}
	
	private void backToMain(){
		Intent i = new Intent(context, MainActivity.class);
		startActivity(i);
		finish();
	}
	
	private double getTotalMonth(){
		List<Item> list = null;
		try {
			list = GastosManager.getInstance(context).getAllItems();
		} catch (SQLException e) {
			
		}
		double total = 0;
		for(Item temp : list){
			total = total + temp.getValorCuota();
		}
		return total;
	}

	private void showMonth() {
		DateFormat df = DateFormat.getDateInstance();
		String month = df.format(new Date(System.currentTimeMillis()));
		actualMonth.setText(month);
	}
	
//	public void deleteItemWeb(Item item){
//		DeleteItemTask task = new DeleteItemTask();
//		task.execute(item);
//	}
	
	private class DeleteAllItemsTask extends AsyncTask<String, Void, Boolean> {

		@Override
		protected Boolean doInBackground(String... params) {
			boolean result = false;
			GastosTarjetaService service = new GastosTarjetaServiceImpl();
			try {
				result = service.deleteAllItems(params[0]);
				Log.d(TAG, "DeleteAllItems - result : " + result);
			} catch (Exception e) {
				Log.e(TAG, "Error en borrar todos los items en la web:  " + e.getMessage(), e);
			} 
			return result;
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			if(result){
				Toast.makeText(context, "Se han borrado todos los items en la web!", Toast.LENGTH_SHORT).show();
			}
		}
		
	}
	
	private class DeleteItemTask extends AsyncTask<Item, Void, Boolean> {

		@Override
		protected Boolean doInBackground(Item... params) {
			boolean result = false;
			GastosTarjetaService service = new GastosTarjetaServiceImpl();
			try {
				Item item = params[0];
				result = service.deleteItem(item.getIdDB());
				Log.d(TAG, "DeleteItem - result : " + result);
			} catch (Exception e) {
				Log.e(TAG, "Error en borrar item en la web:  " + e.getMessage(), e);
			}
			return result;
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			if(result){
				Toast.makeText(context, "Se ha borrado el item en la web!", Toast.LENGTH_SHORT).show();
			}			
		}
	}
}
